package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;
    
    @Autowired
    private MongoTemplate template;
    
    
    @Override
    public StrategyTheme get(String id) {
        return strategyThemeRepository.findById(id).get();
    }

    @Override
    public List<StrategyTheme> selectAll() {
        return strategyThemeRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        //创建Query对象,根据过滤条件查询总条数,此处没有限制条件,所以用空的查询对象查
        Query query = new Query();
        //创建过滤查询
        //有数据,进行分页操作,创建新的分页对象,此索引从0开始,所以要减一,分页的字段与数据库一致
        Pageable pageAble = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "_id");
        //返回给控制器
        return DBHelper.query(template, StrategyTheme.class, query, pageAble);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public void deleteById(String id) {
        strategyThemeRepository.deleteById(id);
    }

    @Override
    public void addThemeName(Strategy strategy) {
        /**
         * 给攻略对象添加主题名
         * @param strategy
         */
        StrategyTheme st = strategyThemeRepository.findById(strategy.getThemeId()).get();
        strategy.setThemeName(st.getName());
    }
}
